'ip变化发送'
import json
import os
import sys
import time

import requests
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.firefox.options import Options

import config
import utils

headers = {
    "User-Agent":
    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36"
}
# 可以保证在任何路径运行，都获取到正确的路径
os.chdir(sys.path[0])
ip_log_dir = os.path.abspath(".") + "/data"
ip_txt = ip_log_dir + "/ip.txt"


def get_net_json():
    """_summary_

    Returns:
        _type_: _description_
    """
    t = int(time.time())
    url0 = "http://login.lzu.edu.cn/cgi-bin/rad_user_info?callback=jQuery1124007666843753697772_"
    r = requests.get(f"{url0}{t}&_={t}", headers=headers, timeout=10)
    data = r.text
    data_json = data.split("(")[1].split(")")[0]
    save_log(data_json)
    jsons = json.loads(data_json)

    return jsons


# 校园网是否已经登录
def is_logined():
    """_summary_

    Returns:
        _type_: _description_
    """
    jsons = get_net_json()

    login_success = jsons["error"] == "ok"
    if login_success:
        s = "网络连接成功!\n"
        net_g = int(jsons["sum_bytes"]) / (1024.0 * 1024.0 * 1024.0)
        s += f"  {jsons["user_name"]}  {jsons["billing_name"]}"
        s += f"  ip: {jsons["online_ip"]}  已经使用 {net_g:.2f}G"
    else:
        s = "网络连接失败!"

    print(s)
    save_log(s)

    return login_success


# 登录校园网
def check_login(usr, pw):
    """暂时不能用，因为校园网登录页面有验证码

    Args:
        usr (_type_): _description_
        pw (_type_): _description_
    """
    if is_logined():
        return
    print("登录中....\n")
    save_log("登录中....\n")

    # 设置chrome为无界面浏览器
    options = Options()
    options.add_argument('--headless')
    # 打开浏览器(火狐)
    driver = webdriver.Firefox(options=options)

    url = "http://login.lzu.edu.cn/"
    driver.get(url)
    print("请等待5s....\n")
    time.sleep(5)

    # 找到输入框并输入查询内容
    id_username = driver.find_element(by=By.ID, value="username")
    id_password = driver.find_element(by=By.ID, value="password")
    id_username.send_keys(usr)
    id_password.send_keys(pw)
    # 提交表单
    driver.find_element(by=By.ID, value="login").click()

    # 关闭浏览器
    driver.close()

    # 杀死chrome浏览器的连接桥(chromedriver)的进程
    driver.quit()

    if not is_logined():
        s = driver.page_source+"\n\n登录错误！仍不在线"
    else:
        s = "\n登录成功！"

    utils.save_log2(s, "login.log", False)
    print(s)

# 注销登录


def logout():
    """_summary_
    """
    if not is_logined():
        return

    print("注销录中....\n")
    save_log("注销录中....\n")

    # 设置chrome为无界面浏览器
    options = Options()
    options.add_argument('--headless')
    # 打开浏览器(火狐)
    driver = webdriver.Firefox(options=options)

    url = "http://login.lzu.edu.cn/"
    driver.get(url)
    # print(driver.page_source)
    # 延迟几秒，加载是否登录的信息
    print("请等待5s....\n")
    time.sleep(5)

    # 提交表单
    driver.find_element(by=By.ID, value="logout-dm").click()

    # 关闭浏览器
    driver.close()

    # 杀死chrome浏览器的连接桥(chromedriver)的进程
    driver.quit()

    utils.save_log2("注销登录", "logout.log", False)

    if is_logined():
        s = driver.page_source+"\n\n注销登录错误！仍然在线"
    else:
        s = "\n注销登录成功！"
    utils.save_log2(s, "login.log", False)
    print(s)


def get_now_ip():
    """_summary_

    Returns:
        _type_: _description_
    """
    jsons = get_net_json()
    now_ip = jsons["online_ip"]
    print(f"现在ip：{now_ip}")

    return now_ip


def save_ip(ip):
    """_summary_

    Args:
        ip (_type_): _description_
    """
    os.makedirs(ip_log_dir, exist_ok=True)
    # 每次获取现在的ip，都把文件中的上次ip更新一下
    with open(ip_txt, 'w', encoding="utf-8") as file:
        file.write(ip)


def get_last_ip():
    """_summary_

    Returns:
        _type_: _description_
    """
    last_ip = ""

    if os.path.exists(ip_txt):
        with open(ip_txt, 'r', encoding="utf-8") as file:
            last_ip = file.read()

    print(f"上次ip：{last_ip}")
    return last_ip


def save_log(content):
    """_summary_

    Args:
        content (_type_): _description_
    """
    utils.save_log2(content, "ip.log", False)


def control_ip():
    """_summary_
    """
    last = get_last_ip()
    now = get_now_ip()

    content = "现在的ip是：" + now + "\n" + "上次是：" + last

    if last != now:
        save_ip(now)
        utils.send_mails(f"{config.PC_NAME}: ip发生变化", content)
    else:
        print("ip未发生变化：" + now)
        save_log("ip未发生变化" + content)


def main():
    """_summary_
    """
    check_login(config.LZU_USER, config.LZU_PW)
    control_ip()


if __name__ == '__main__':

    # “电脑连上电源自动开机”（防止断电关机）

    # 方法一：自己设置系统的定时任务，定时任务启动这个程序,保证开机以后程序
    main()
    # logout()

    # # 方法二：保证开机以后这个程序运行,程序自身会定期运行
    # # 需要安装 apscheduler
    # from apscheduler.schedulers.blocking import BlockingScheduler

    # scheduler = BlockingScheduler()
    # # 添加任务并设置触发方式为s
    # scheduler.add_job(main, 'interval', seconds=120)  #2分钟检查一次ip
    # #开始运行调度器
    # scheduler.start()
